<?php

//index.php?fc=module&module=fichevitrine&controller=editor
require_once _PS_MODULE_DIR_ . 'fichevitrine/models/FicheAbo.php';
require_once _PS_MODULE_DIR_ . 'fichevitrine/models/Fiche.php';
require_once _PS_MODULE_DIR_ . 'fichevitrine/models/FicheTheme.php';
require_once _PS_MODULE_DIR_ . 'fichevitrine/models/FicheProp.php';
require_once _PS_MODULE_DIR_ . 'fichevitrine/controllers/front/VitrineFrontController.php';

/**
 * 
 * @author Nicolas Legrand <n.legrand28@gmail.com>
 */
class FicheVitrine extends Module 
{
	
	public function __construct() 
	{
		$this->name 		= 'fichevitrine';
		$this->tab 		= 'front_office_features';
		$this->version 		= 1.0;
		$this->author 		= 'The Tiny Spark';
		$this->displayName 	= $this->l('Fiche Vitrine');

		parent :: __construct();
	}

	public function hookNewOrder($params)
	{
		return $this->hookActionOrderStatusPostUpdate($params);
	}

	public function hookActionOrderStatusPostUpdate($params)
	{
		// à chaque commande
		// etape 1: vérifier que le client prestashop possède un compte abonnement fiche vitrine
		// si il en possède déjà un on ne lui offre rien du tout
		// si il n'en possède pas à ce moment là on crée son compte abonnement fiche vitrine
		// et on lui offre un certain nombre de jours gratuits
		// sauf si sa première commande comporte les produits lfv_month ou lfv_week
		if ( !isset($params) || !isset($params['newOrderStatus']) )
			return;
		
		$status = $params['newOrderStatus'];
		$cart = $params['cart'];
		$products = $cart->getProducts(true);
		$id_customer = $cart->id_customer;
		$by = 0;
		
		if ( $status->paid == 0 || ( $status->id != 12 && $status->id != 2 ) )
			return;
			
		foreach( $products as $currentProduct )
		{
			$reference = strtolower($currentProduct['reference']);
			
			if ( strpos($reference, 'lfv_month') > -1 )
			{
				$by += (3600 * 24 * 31);
			}
			else if ( strpos($reference, 'lfv_week') > -1 )
			{
				$by += (3600 * 24 * 7);
			}
		}
		
		FicheAbo::setAboEndBy($id_customer, $by );
	}
	
	public function hookactionPaymentConfirmation(){}// never called ? 
	
	public function install() 
	{
		$ok = parent :: install();
		//$ok = $ok && $this->resetDb();
		$ok = $ok && $this->prepareHooks();
		$ok = $ok && $this->initConfig();
		Fiche::rewriteDynamicTranslations();
		return $ok;
	}
	
	private function prepareHooks()
	{
		$hooks = array('actionOrderStatusPostUpdate','newOrder');
		
		foreach( $hooks as $hook )
		{
			if ( $this->registerHook($hook) == false )
				return false;
		}
		
		return true;
	}
	
	private function createFicheAboTable()
	{
		$statements = array();
		
		$statement1 = "DROP TABLE IF EXISTS `"._DB_PREFIX_ ."ficheAbo`";
		$statement2 = "CREATE TABLE `"._DB_PREFIX_."ficheAbo` (";
		$statement2 .= '`id_abo` int(10) unsigned NOT NULL AUTO_INCREMENT,';
		$statement2 .= '`id_customer` int(10) unsigned NOT NULL,';
		$statement2 .= '`customer_firstname` VARCHAR(255) NOT NULL,';
		$statement2 .= '`customer_lastname` VARCHAR(255) NOT NULL,';
		$statement2 .= '`customer_email` VARCHAR(255) NOT NULL,';
		$statement2 .= '`date_start` TIMESTAMP NOT NULL DEFAULT NOW(),';
		$statement2 .= '`date_end` TIMESTAMP NOT NULL,';
		$statement2 .= '`storeSize` int(10) NOT NULL,';
		$statement2 .= '`twoInOne` int(10) NOT NULL,';
		$statement2 .= 'PRIMARY KEY (`id_abo`)';
		$statement2 .= ") ENGINE="._MYSQL_ENGINE_;
		
		$statements[] = $statement1;
		$statements[] = $statement2;

		foreach ($statements as $statement) {
			if (!Db :: getInstance()->Execute($statement)) {
				return false;
			}
		}
		
		return true;
	}
	
	private function createFicheTable()
	{
		$statements = array();
		
		$statement1 = "DROP TABLE IF EXISTS `"._DB_PREFIX_ ."fiche`";
		$statement2 = "CREATE TABLE `"._DB_PREFIX_."fiche` (";
		$statement2 .= '`id_fiche` int(10) unsigned NOT NULL AUTO_INCREMENT,';
		$statement2 .= '`id_customer` int(10) unsigned NOT NULL,';
		$statement2 .= '`type` int(1) NOT NULL,';
		$statement2 .= '`data` text NOT NULL,';
		$statement2 .= '`date` TIMESTAMP NOT NULL DEFAULT NOW(),';
		$statement2 .= '`date_modif` TIMESTAMP NOT NULL,';
		$statement2 .= '`name` VARCHAR(255) NOT NULL,';
		$statement2 .= '`weight` int(32) NOT NULL,';
		$statement2 .= '`modelId` int(32) NOT NULL,';
		$statement2 .= '`propId` int(32) NOT NULL,';
		$statement2 .= '`public` int(1) NOT NULL,';
		$statement2 .= '`theme` int(10) NOT NULL,';
		$statement2 .= '`format` VARCHAR(255) NOT NULL,';
		$statement2 .= '`orientation` int(10) NOT NULL DEFAULT 0,';
		$statement2 .= '`active` int(1) NOT NULL,';
		$statement2 .= '`rent` int(1) NOT NULL,';
		$statement2 .= 'PRIMARY KEY (`id_fiche`)';
		$statement2 .= ") ENGINE="._MYSQL_ENGINE_;
		
		$statements[] = $statement1;
		$statements[] = $statement2;

		foreach ($statements as $statement) {
			if (!Db :: getInstance()->Execute($statement)) {
				return false;
			}
		}
		
		return true;
	}
	
	private function createPropTable()
	{
		$statements = array();
		
		$statement1 = "DROP TABLE IF EXISTS `"._DB_PREFIX_ ."ficheprop`";
		
		$statement2 = "CREATE TABLE `"._DB_PREFIX_."ficheprop` (";
		$statement2 .= '`id_prop` int(10) unsigned NOT NULL AUTO_INCREMENT,';
		$statement2 .= '`name` VARCHAR(255) NOT NULL,';
		$statement2 .= 'PRIMARY KEY (`id_prop`)';
		$statement2 .= ") ENGINE="._MYSQL_ENGINE_;
		
		$statements[] = $statement1;
		$statements[] = $statement2;
		
		$statements[] = "INSERT INTO `"._DB_PREFIX_."ficheprop` VALUES(null,'Maison')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."ficheprop` VALUES(null,'Villa')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."ficheprop` VALUES(null,'Appartement')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."ficheprop` VALUES(null,'Loft')";

		foreach ($statements as $statement) {
			if (!Db :: getInstance()->Execute($statement)) {
				return false;
			}
		}
		
		return true;
	}
		
	private function createThemeTable()
	{
		$statements = array();
		
		$statement1 = "DROP TABLE IF EXISTS `"._DB_PREFIX_ ."fichetheme`";
		
		$statement2 = "CREATE TABLE `"._DB_PREFIX_."fichetheme` (";
		$statement2 .= '`id_theme` int(10) unsigned NOT NULL AUTO_INCREMENT,';
		$statement2 .= '`name` VARCHAR(255) NOT NULL,';
		$statement2 .= 'PRIMARY KEY (`id_theme`)';
		$statement2 .= ") ENGINE="._MYSQL_ENGINE_;
		
		$statements[] = $statement1;
		$statements[] = $statement2;
		
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Abstrait')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Urbain')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Paysage')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Nature')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Vierge')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Noël')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Pâques')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Hiver')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Printemps')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Ete')";
		$statements[] = "INSERT INTO `"._DB_PREFIX_."fichetheme` VALUES(null,'Automne')";

		foreach ($statements as $statement) {
			if (!Db :: getInstance()->Execute($statement)) {
				return false;
			}
		}
		
		return true;
	}
	
	private function initConfig()
	{
		Configuration::deleteByName('fichevitrine_autoSaveTime_');
		Configuration::deleteByName('fichevitrine_autoSave_');
		Configuration::deleteByName('fichevitrine_fontList_');
		Configuration::deleteByName('fichevitrine_fontSizeStart_');
		Configuration::deleteByName('fichevitrine_fontSizeEnd_');
		Configuration::deleteByName('fichevitrine_adminKey_');
		
		Configuration::updateValue('fichevitrine_autoSaveTime_', 10);
		Configuration::updateValue('fichevitrine_autoSave_', 1);
		Configuration::updateValue('fichevitrine_fontList_', 'Verdana,Times New Roman,Sans-serif,Arial,Georgia');
		Configuration::updateValue('fichevitrine_fontSizeStart_', 0);
		Configuration::updateValue('fichevitrine_fontSizeEnd_', 48);
		Configuration::updateValue('fichevitrine_adminKey_', md5('fichevitrine'.rand(0, 1000)));
		
		return true;
	}
	
	public function resetDb()
	{
		$ok = true;
		$ok = $ok && $this->createThemeTable();
		$ok = $ok && $this->createFicheTable();
		$ok = $ok && $this->createFicheAboTable();
		$ok = $ok && $this->createPropTable();
	
		return $ok;
	}	
	
	public function getContent()
	{	
		$link = new Link();
		$ficheLink = $link->getAdminLink('AdminFiche', true);
		
		return '<a href="'.$ficheLink.'">Cliquez ici pour accéder à l\'espace administrateur</a>';
	}
}
